package com.ruoyi.monitorTools.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.ZipUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.GeoJsonUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.monitorTools.domain.RegionalInfo;
import com.ruoyi.monitorTools.mapper.RegionalInfoMapper;
import com.ruoyi.monitorTools.service.RegionalInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.File;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
* @author Administrator
* @description 针对表【regional_info(区域信息表)】的数据库操作Service实现
* @createDate 2025-02-10 18:58:41
*/
@Slf4j
@Service
public class RegionalInfoServiceImpl extends ServiceImpl<RegionalInfoMapper, RegionalInfo>
    implements RegionalInfoService {

    @Autowired
    private RegionalInfoMapper regionalInfoMapper;

    @Override
    public Long addRegional(RegionalInfo regionalInfo) {
        if(StringUtils.isNotBlank(regionalInfo.getRegionGeojson())){
            try {
                regionalInfo.setRegionGeo(GeoJsonUtils.convertGeoJsonToWkt(regionalInfo.getRegionGeojson()));
                regionalInfoMapper.insertOne(regionalInfo);
            } catch (Exception e) {
                log.error("解析geojson失败", e);
                throw new ServiceException("解析上传的区域失败");
            }
        }
        return regionalInfo.getId();
    }

    @Override
    public AjaxResult analyzingBoundary(String filePath) {
        File zipFile = null;
        File outFile = null;
        try {
            filePath = filePath.replace(Constants.RESOURCE_PREFIX, RuoYiConfig.getProfile());
            zipFile = new File(filePath);
            String zipName = zipFile.getName().substring(0, zipFile.getName().lastIndexOf("."));
            String zipOutPath = zipFile.getAbsoluteFile().getParentFile() + File.separator + zipName;
            outFile = new File(zipOutPath);
            outFile.mkdir();
            ZipUtil.unzip(zipFile, outFile.getAbsoluteFile(), Charset.forName("gbk"));
            List<String> shpPaths = searchShpFiles(outFile);
            if (shpPaths.isEmpty() || shpPaths.size() > 1) {
                throw new ServiceException(shpPaths.isEmpty() ? "未找到shp文件" : "只能有一个shp文件");
            }
            String outerBoundaryGeoJSON = GeoJsonUtils.getOuterBoundaryGeoJSON(shpPaths.get(0));
            Map map = JSONObject.parseObject(outerBoundaryGeoJSON, Map.class);

            return AjaxResult.success(map.get("geometry"));
        } catch (Exception e){
            if(e instanceof ServiceException){
                throw (ServiceException) e;
            } else {
                log.error("解析失败", e);
                return AjaxResult.error("");
            }
        } finally {
            if(ObjectUtil.isNotNull(zipFile) && zipFile.exists()){
                FileUtil.del(zipFile);
            }
            if(ObjectUtil.isNotNull(outFile) && zipFile.exists()){
                FileUtil.del(outFile);
            }
        }
    }

    @Override
    public List<RegionalInfo> selectOtherList(Integer type) {

        return null;
    }

    public static List<String> searchShpFiles(File directory) {
        List<String> shpFiles = new ArrayList<>();
        if (directory.isDirectory()) {
            File[] files = directory.listFiles();
            if (files != null) {
                for (File file : files) {
                    if (file.isDirectory()) {
                        // 递归搜索子目录
                        shpFiles.addAll(searchShpFiles(file));
                    } else if (file.getName().endsWith(".shp")) {
                        // 如果是 .shp 文件，添加其路径到列表中
                        shpFiles.add(file.getAbsolutePath());
                    }
                }
            }
        }
        return shpFiles;
    }


}




